//
//  HWSearchController.m
//  HWanGame
//
//  Created by Chendaobin on 2019/8/27.
//  Copyright © 2019年 Chendaobin. All rights reserved.
//

#import "HWSearchController.h"
#import "HWSearchViewCell.h"
#import "HWResultsSearchViewController.h"


@interface HWSearchController ()<UITextFieldDelegate,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate>
@property(weak,nonatomic) UITextField *searchTextField;
@property(strong,nonatomic) UICollectionView *maincollectionView;
@property(strong,nonatomic)  NSArray  *diyigeArr;
@property(strong,nonatomic)  NSMutableArray * ergeArr;
@property(assign,nonatomic)NSInteger sectionnumube;


@end

@implementation HWSearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSMutableArray *jiluData =   [defaults objectForKey:@"seachjilu"];
    
    
    if (jiluData != nil) {
        
      
        
    } else  {
        
        NSMutableArray *mutab = [[NSMutableArray alloc]init];
        
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        [defaults setObject:mutab forKey:@"seachjilu"];
        [defaults synchronize];
        
        
        
    }
//    NSMutableArray *mutab = [[NSMutableArray alloc]init];
//
//    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
//
//
//    [defaults setObject:mutab forKey:@"seachjilu"];
//
    //设置常用的属性
    [self commonlyUsedAttributes];
    
    // 设置UI
    [self setUpUiView];
    // 设置导航栏
    [self setupNavigation];
    
    //传奇
    
     //热门搜索
    [self hotSearch];
    
    
    
    
    
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSMutableArray *jiluData =   [defaults objectForKey:@"seachjilu"];
    
    self.ergeArr = jiluData;
    if (jiluData.count > 0) {
        self.sectionnumube = 3;
        [self.maincollectionView reloadData];
    }
   // [self.maincollectionView reloadData];
    
    
    
}




- (void)hotSearch {
    
    NSDictionary *parametes = @{
                                @"ios" : @"1",
                                @"ct" :  @"app",
                                @"ac" : @"hot_so"
                                };
    
    [HWWebUtils doGetWithParameters:parametes progress:nil success:^(id response) {
        
        NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
        
        if ([codeStr intValue] == 1) {
            
            self.diyigeArr = response[@"data"];
            [self.maincollectionView reloadData];
            
    
        }
     
        
        
    } failure:^(NSString *error) {
        
        
       
        
    }];

    
    
    
    
}





// 设置常用的属性
- (void)commonlyUsedAttributes {
    
    self.sectionnumube = 2;
   // self.ergeArr = @[@"网游",@"测旅",@"网游",@"测旅",@"网游",@"测旅",@"BT",@"传奇霸业",@"西方魔幻"];
    
//   CGSize siez = [WMUtil  strName:@"BT" fontSize:[UIFont systemFontOfSize:12] boundingRectWithSize:CGSizeMake(200, 27)];
    
  //  NSLog(@"dai %f",siez.width);
    
    
    
}


// 设置UI
- (void)setUpUiView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    CGFloat jianju =  (kScreenW - 78*4 -20)/3;
    layout.minimumLineSpacing = 12;
    layout.minimumInteritemSpacing = 10;
    
    self.maincollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,  StatusBarHeight+44+5, kScreenW,kScreenH -NavBarHeight) collectionViewLayout:layout];
  //  self.maincollectionView.showsHorizontalScrollIndicator = NO;
    self.maincollectionView.delegate = self;
    self.maincollectionView.dataSource = self;
    self.maincollectionView.backgroundColor = [UIColor whiteColor];
 //   self.maincollectionView.backgroundColor = RGB(217, 247, 250);
    //self.maincollectionView.alwaysBounceHorizontal = YES;
   self.maincollectionView.contentInset = UIEdgeInsetsMake(0, 25, 0, 25);
    // [self.maincollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];  //  一定要设置
  //  [self.maincollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellID"];
    [self.maincollectionView  registerNib:[UINib nibWithNibName:@"HWSearchViewCell" bundle:nil] forCellWithReuseIdentifier:@"cellID"];
   [self.maincollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    self.maincollectionView.userInteractionEnabled = YES;
    [self.view  addSubview:self.maincollectionView];
    
    
}

//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//
//    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//
//
//
//}


#pragma mark ------- 设置导航栏
- (void)setupNavigation {
    

    
    UIView * naviView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, StatusBarHeight+44)];
   // naviView.backgroundColor = [UIColor redColor];
    [self.view addSubview:naviView];
    
    
  
    UITextField *texfeild = [[UITextField alloc]initWithFrame:CGRectMake(15, StatusBarHeight+ 7, kScreenW-15-55, 30)];
    texfeild.returnKeyType =UIReturnKeySearch;
    texfeild.delegate = self;
    texfeild.placeholder = @"输入你要搜索的游戏";
    
    texfeild.placeholder  =  [HWjianzhiduiObject keylocalization:@"输入你要搜索的游戏"];
    
    //    texfeild.layer.borderColor  = RGB(208, 208, 208).CGColor;
    //    texfeild.layer.borderWidth = 0.5;
//    texfeild.font = [UIFont systemFontOfSize:12];
//    UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
//    button.frame = CGRectMake(0, 0, 30, 30);
//    [button setImage:[UIImage imageNamed:@"sousukuananniu_ico"] forState:UIControlStateNormal];
//    [button setImage:[UIImage imageNamed:@"sousukuananniu_ico"] forState:UIControlStateHighlighted];
    
    UIView *sousuoView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 32)];
        UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(5, 0, 30, 30);
        [button setImage:[UIImage imageNamed:@"sousukuananniu_ico"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"sousukuananniu_ico"] forState:UIControlStateHighlighted];
       [sousuoView addSubview:button];
    
    
    texfeild.leftView = sousuoView;
    texfeild.leftViewMode = UITextFieldViewModeAlways;
    texfeild.layer.cornerRadius = 15;
    texfeild.layer.masksToBounds = YES;
    texfeild.backgroundColor = RGB(245, 245, 245);
    //   [texfeild becomeFirstResponder];
    [naviView addSubview:texfeild];
    self.searchTextField = texfeild;
    
     UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
     cancelButton.frame = CGRectMake(kScreenW-60, StatusBarHeight, 55, 44);
    
    // 热门
    NSString *quxiaoStr = [HWjianzhiduiObject keylocalization:@"取消"];
    
    
    
     [cancelButton setTitle:quxiaoStr forState:UIControlStateNormal];
     [cancelButton setTitle:quxiaoStr forState:UIControlStateHighlighted];
    
    
    
    
     [cancelButton setTitleColor:RGB(51, 52,49) forState:UIControlStateNormal];
     [cancelButton setTitleColor:RGB(51, 52,49) forState:UIControlStateHighlighted];
    
    
     [cancelButton addTarget:self action:@selector(cancelButtonTap) forControlEvents:UIControlEventTouchUpInside];
     [naviView addSubview:cancelButton];
    

}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"12345");
    
    [self searchRutanjieguo];
    
    
    
    return  YES;
    
    
}

- (void)cancelButtonTap {
    
    
    [self.searchTextField canResignFirstResponder];
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    
}


#pragma  mark ------ UICollectionViewDataSource

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    
    return  self.sectionnumube;
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
      return  0;
        
        
    } else if (section == 1) {
        return   self.diyigeArr.count;
    } else {
         return   self.ergeArr.count;
    }
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HWSearchViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];

    if (indexPath.section == 0) {

      
        
        
    } else  if(indexPath.section == 1){
        
        cell.index = indexPath;
        NSDictionary *dic = self.diyigeArr[indexPath.row];
        cell.nameLabel.text = dic[@"name"];
       
        
    } else {
        
        cell.nameLabel.backgroundColor = RGB(245, 245, 245);
        cell.nameLabel.textColor = RGB(102, 102, 97);
        cell.nameLabel.text = self.ergeArr[indexPath.row];
        
    }
    
    

    return cell;

}














- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
      
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenW - 2*25-89)/2, 5, 89, 111)];
      //  imageView.backgroundColor = [UIColor orangeColor];
        
        UIButton *deleBut = [UIButton buttonWithType:UIButtonTypeCustom];
        deleBut.frame = CGRectMake(kScreenW-50-15, 17, 16, 35);
      //  deleBut.backgroundColor = [UIColor redColor];
        [deleBut setImage:[UIImage imageNamed:@"Shape"] forState:UIControlStateNormal];
        [deleBut addTarget:self action:@selector(delegatTap) forControlEvents:UIControlEventTouchUpInside];
        
    
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 17, kScreenW - 2*25, 35)];
    
        label.textColor  = RGB(51, 51, 49);
        label.font = [UIFont systemFontOfSize:14];
    
        if (indexPath.section == 0) {
          //  label.text = @"热门搜索";
            
           // [header addSubview:imageView];
            header.backgroundColor = [UIColor whiteColor];
            
            
            
            
        } else if(indexPath.section == 1) {
            
            label.text = @"热门搜索";
            label.text = [HWjianzhiduiObject keylocalization:@"热门搜索"];
            
             
            
        
            
        } else {
            
           
              label.text = @"搜索历史";
        }
        
        
        
        
        
        for (UIView *view in header.subviews) {
            [view removeFromSuperview];
        } // 防止复用分区头
        //[header addSubview:button];
        
        if (indexPath.section == 0) {
            
             [header addSubview:imageView];
            
        } else  if(indexPath.section == 1)  {
             [header addSubview:label];
           // [header addSubview:deleBut];
        } else {
             [header addSubview:label];
              [header addSubview:deleBut];
            
        }
      //  [header addSubview:label];
        
        return header;
    } else {
        return nil;
    }
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *str  = nil;

    if (indexPath.section == 0) {
        
        
      //  CGSizeMake(kScreenW - 2*25, 111+10+16+10);
        
    } else if (indexPath.section == 1) {
        
        NSDictionary *dic  = self.diyigeArr[indexPath.row];
        
        str = dic[@"name"];
        
    } else {
        
           str = self.ergeArr[indexPath.row];
    }

    CGSize size = [WMUtil  strName:str fontSize:[UIFont systemFontOfSize:12] boundingRectWithSize:CGSizeMake(200, 27)];
    
    CGFloat width = size.width + 20;
    
    if (width < 44) {
        width = 44;
    }
    
    return CGSizeMake(width,27);
    
    

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        
      return    CGSizeMake(0, 0);
        
    } else if (section == 1) {
        
         return   CGSizeMake(kScreenW, 35+6+17);
    }else  {
        return   CGSizeMake(kScreenW, 35+6+17);
        
    }
    
    
    
}

#pragma mark -------

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section == 1) {
        
        
        NSDictionary *dict = self.diyigeArr[indexPath.row];
        NSString *str = dict[@"name"];
        
        HWResultsSearchViewController *resuleSea = [[HWResultsSearchViewController alloc]init];
      //  resuleSea.panduStr = @"1";
        resuleSea.keyword =str;
        UINavigationController *na = [[UINavigationController alloc]initWithRootViewController:resuleSea];
         na.modalPresentationStyle = UIModalPresentationOverFullScreen;
        
        [self presentViewController:na animated:YES completion:nil];
    
        
    } else if (indexPath.section == 2) {
        
        
        
        HWResultsSearchViewController *resuleSea = [[HWResultsSearchViewController alloc]init];
        //  resuleSea.panduStr = @"1";
        resuleSea.keyword = self.ergeArr[indexPath.row];
        resuleSea.panduStr = @"1";
        UINavigationController *na = [[UINavigationController alloc]initWithRootViewController:resuleSea];
        na.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:na animated:YES completion:nil];
        
        
    }
    
    
}


#pragma mark ------  点击删除按钮
- (void)delegatTap {
    
    DLog(@"删除按钮");
    
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSMutableArray *jiluData =   [((NSMutableArray *)[defaults objectForKey:@"seachjilu"]) mutableCopy];
    
    
    if (jiluData != nil) {
        
        [jiluData removeAllObjects];
        [defaults setObject:jiluData forKey:@"seachjilu"];
        [defaults synchronize];
        
        self.sectionnumube = 2;
        [self.maincollectionView reloadData];
        
        
        
    } else  {
        
   
        
        
        
    }
    
}





#pragma  mark ---------  点击搜索按钮
- (void)searchRutanjieguo {
    
    if (self.searchTextField.text.length > 0) {
        DLog(@"大");
        [self.searchTextField resignFirstResponder];
        
      
        HWResultsSearchViewController *resuleSea = [[HWResultsSearchViewController alloc]init];
        resuleSea.keyword = self.searchTextField.text;
        resuleSea.panduStr = @"1";
        UINavigationController *na = [[UINavigationController alloc]initWithRootViewController:resuleSea];
        na.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:na animated:YES completion:nil];
       
        
    
        
        
        
        
        
    } else {
        
         DLog(@"小");
        [self.searchTextField resignFirstResponder];
        
        
        
    }
    

    
}



@end
